package com.example.medicalzb.service;

import com.example.medicalzb.entity.DrugEntity;
import com.example.medicalzb.mapper.DrugMapper;
import com.example.medicalzb.model.DrugModel;
import com.example.medicalzb.param.DrugParam;
import com.example.medicalzb.util.Msg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DrugService {
    @Autowired
    private DrugMapper drugMapper;
    public PageInfo<DrugModel> getDrugWithPage(Integer pn, Integer size, String name) {
        PageHelper.startPage(pn,size);
        List<DrugModel> list = drugMapper.getAllDrug(name);
        PageInfo<DrugModel> pageInfo = new PageInfo<>(list,5);
        return pageInfo;
    }

    public Msg saveDrug(DrugParam drugParam) {
        drugParam.setCreatetime(new DateTime().toDate());
        drugParam.setUpdatetime(new DateTime().toDate());
        DrugEntity drugEntity = new DrugEntity();
        BeanUtils.copyProperties(drugParam,drugEntity);
        int i = drugMapper.saveDrug(drugEntity);
        int j = drugMapper.insertSalePlace(drugEntity.getDrugId(),drugParam.getSaleIds());
        drugEntity.setTotal((long) drugMapper.getAllDrug(null).size());
        if (i > 0 && j > 0){
            Long num = drugEntity.getTotal() % 5 == 0 ? (drugEntity.getTotal() / 5) : ((drugEntity.getTotal() / 5) + 1);
            return Msg.success().data("pages",num).mess("添加成功");
        }
        return Msg.fail().mess("添加失败");
    }

    public Msg updateDrug(Long id, DrugParam drugParam) {
        drugParam.setUpdatetime(new DateTime().toDate());
        drugParam.setDrugId(id);
        DrugEntity drugEntity = new DrugEntity();
        BeanUtils.copyProperties(drugParam,drugEntity);
        drugMapper.deleteSaleByDrugId(drugEntity.getDrugId());
        drugMapper.insertSalePlace(drugEntity.getDrugId(),drugParam.getSaleIds());
        int i = drugMapper.updateDrug(drugEntity);
        if (i > 0){
            return Msg.success().mess("修改药品信息成功");
        }
        return Msg.fail().mess("修改药品信息失败");
    }

    public Msg deleteDrug(Long id) {
        drugMapper.deleteSaleByDrugId(id);
        int i = drugMapper.deleteDrugById(id);
        if (i > 0){
            return Msg.success().mess("删除药品成功");
        }
        return Msg.fail().mess("删除药品失败");
    }
}
